//
//  HomeController.m
//  敢唆嘛!
//
//  Created by 教主 on 15/11/23.
//  Copyright © 2015年 zms. All rights reserved.
//

// 首页controller
#import "HomeController.h"
#import "Device.h"
#import "Define.h"
#import "HomeCell.h"
#import "HomeHeader.h"
#import "HomeModel.h"
#import "HomeHeaderModel.h"
#import "DetailController.h"
#import "MBProgressHUD.h"
#import "MainController.h"

@interface HomeController () <UITableViewDataSource, UITableViewDelegate, MBProgressHUDDelegate>
@property(nonatomic, strong)UITableView *homeTableView;         // home主页界面tableView
@property(nonatomic, strong)NSMutableArray *homeModelArray;     // 接收数据的model
@property(nonatomic, strong)NSMutableArray *headerModelArray;   // 接收广告图片
@property(nonatomic, strong)NSString *reloadState;             // 收藏刷新状态
@property(nonatomic, strong)MBProgressHUD *hud;
@end

static NSString *cellIdentifier = @"cell";
@implementation HomeController
{
    NSInteger limitNumber;  // 分页查询记录
}

// 查询bmob数据库表内所有内容 最多1000 默认100
- (void)findHomeHeader
{
    MainController *mainVc = (MainController *)self.parentViewController;
    // 查询广告表
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"HomeHeader"];
    bquery.limit = 1000;
    //查找Recommend表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error)
        {
            // 判断网络连接
            if (![[NetWorkState shareInstance] reachability])
            {
                [self alertActionWithTitle:@"提示" message:@"网络不通" other:@"确定"];
            };
            NSLog(@"error:%@",error);
        }
        else
        {
            // 数据请求成功后才初始化数组 否则会造成下拉刷新崩溃
            self.headerModelArray = [NSMutableArray array];
            for (BmobObject *obj in array)
            {
                NSLog(@"%ld",array.count);
                HomeHeaderModel *model = [[HomeHeaderModel alloc] initWithObj:obj];
                [self.headerModelArray addObject:model];
            }
            // 需要在主线程里面进行刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.homeTableView reloadData];
                
            });
        }
    }];
}

// 查询bmob数据库表内所有内容 最多1000 默认100
- (void)findAllHomeData:(NSInteger)limit
{
    //找到滚动视图
    MainController *mainVc = (MainController *)self.parentViewController;
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"RecommendHome"];
    [bquery orderByDescending:@"createdAt"];
    bquery.limit = limit;
    //查找Recommend表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error)
        {
            // 判断网络连接
            if (![[NetWorkState shareInstance] reachability])
            {
                [self alertActionWithTitle:@"提示" message:@"网络不通" other:@"确定"];
            };
            NSLog(@"error:%@",error);
            // 禁用滑动
            [mainVc scrollOnorOff:NO];
        }
        else
        {
            // 数据请求成功后才初始化数组 否则会造成下拉刷新崩溃
            self.homeModelArray = [NSMutableArray array];
            for (BmobObject *obj in array)
            {
                HomeModel *model = [[HomeModel alloc] initWithObj:obj];
                // 条用多条查询 来获取多个用户头像
                [self findUserDataWith:model];
                // 来得到该条数据的 推荐数,分享数,评论数,类型
                [self getRealityDataWith:model];
                [self.homeModelArray addObject:model];
            }
            // 需要在主线程里面进行刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 隐藏转菊花
                [self.hud hide:YES];
                // 开启滑动
                [mainVc scrollOnorOff:YES];
                [self.homeTableView reloadData];
                [self.homeTableView.header endRefreshing];
                [self.homeTableView.footer endRefreshing];
            });
        }
    }];
}

// 查询单条 真事
- (void)getRealityDataWith:(HomeModel *)model
{
    //查找Reality表单条数据
#warning 更改表
    NSString *className = nil;
    if ([model.type isEqualToString:@"真事"])
    {
        className = @"Reality";
    }
    else if ([model.type isEqualToString:@"创作"])
    {
        className = @"Creation";
    }
    else if ([model.type isEqualToString:@"游记"])
    {
        className = @"Travel";
    }
    else if ([model.type isEqualToString:@"秘密"])
    {
        className = @"Secret";
    }

    BmobQuery *bquery = [BmobQuery queryWithClassName:className];
    [bquery getObjectInBackgroundWithId:model.realityObjectId block:^(BmobObject *object,NSError *error){
        if (error)
        {
            // 判断网络连接
            if (![[NetWorkState shareInstance] reachability])
            {
                [self alertActionWithTitle:@"提示" message:@"网络不通" other:@"确定"];
            };
            NSLog(@"error:%@",error);
        }
        else
        {
            //表里有id为model.realityObjectId的数据
            if (object)
            {
                // 找到相同的用户账号 来得到该条数据的 推荐数,分享数,评论数,类型
                if ([model.userName isEqualToString:[object objectForKey:@"userName"]])
                {
                    model.realityCreatedAt = [object objectForKey:@"createdAt"];
                    BmobFile *infoImageFile = [object objectForKey:@"infoImage"];
                    model.infoImage = infoImageFile.url;
                    model.recommendNumber = [[object objectForKey:@"recommendNumber"] integerValue];
                    model.collectNumber = [[object objectForKey:@"collectNumber"] integerValue];
                    model.commentNumber = [[object objectForKey:@"commentNumber"] integerValue];
                    BmobFile *infoTitleImageFile = [object objectForKey:@"infoTitleImage"];
                    model.infoTitleImage = infoTitleImageFile.url;
                    model.shareNumber = [[object objectForKey:@"shareNumber"] integerValue];
                }
            }
            // 需要在主线程里面进行刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.homeTableView reloadData];
            });
        }
    }];
}

// 查询bmob数据库表内所有内容 最多1000 默认100  查找用户
- (void)findUserDataWith:(HomeModel *)model
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
    bquery.limit = 1000;
    //查找Recommend表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error)
        {
            // 判断网络连接
            if (![[NetWorkState shareInstance] reachability])
            {
                [self alertActionWithTitle:@"提示" message:@"网络不通" other:@"确定"];
            };
            NSLog(@"error:%@",error);
        }
        else
        {
            for (BmobObject *obj in array)
            {
                // 找到相同的用户账号 来得到推荐人头像
                if ([model.recommendUserName isEqualToString:[obj objectForKey:@"username"]])
                {
                    BmobFile *recommendUserHeaderFile = [obj objectForKey:@"userHeader"];
                    model.recommendUserHeader = recommendUserHeaderFile.url;
                }
                // 得到被推荐的头像
                if ([model.userName isEqualToString:[obj objectForKey:@"username"]])
                {
                    BmobFile *userHeaderFile = [obj objectForKey:@"userHeader"];
                    model.userHeader = userHeaderFile.url;
                }
            }
            // 需要在主线程里面进行刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.homeTableView reloadData];
            });
        }
    }];
}

//视图将要出现的时候重新请求数据  数据是改变收藏的新数据
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
    // 刷新收藏的数量
    if ([self.reloadState isEqualToString:@"reload"])
    {
        [self findAllHomeData:limitNumber];
        self.reloadState = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建tableView
    self.homeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KSWidth, KSHeight - 64) style:UITableViewStyleGrouped];
//    self.homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.homeTableView.delegate = self;
    self.homeTableView.dataSource = self;
    self.homeTableView.backgroundColor = [UIColor whiteColor];
    
    //注册自定义cell
    [self.homeTableView registerClass:[HomeCell class] forCellReuseIdentifier:cellIdentifier];
    // 创建分区头
    [self.homeTableView registerClass:[HomeHeader class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.view addSubview:_homeTableView];
    
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_hud];
//    self.hud.mode = MBProgressHUDModeDeterminate;
    self.hud.delegate = self;
    self.hud.labelText = @"Loading";
    // 显示转菊花
    [self.hud show:YES];
    
    limitNumber = 10;
    // 调用首页数据
    [self findAllHomeData:limitNumber];
    // 调用首页广告数据
    [self findHomeHeader];
    
    // 添加下拉刷新
    [self.homeTableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefreshing)];
    // 添加上拉加载更多
    [self.homeTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
    
    // 创建收藏刷新通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(collectRefreshing:) name:@"reload" object:nil];
    
}

// 刷新收藏数
- (void)collectRefreshing:(NSNotification *)collect
{
    self.reloadState = (NSString *)collect.object;
}

// 下拉刷新
- (void)headerRefreshing
{
    // 刷新调用
    [self findAllHomeData:limitNumber];
}

// 上拉加载更多
- (void)footerRefreshing
{
    limitNumber += 5;
    // 刷新调用
    [self findAllHomeData:limitNumber];
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.homeModelArray[indexPath.row];
    
    
    return cell;
}

// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailController *detailVc = [[DetailController alloc] init];
    
    detailVc.homeModel = self.homeModelArray[indexPath.row];
    
    [self.navigationController pushViewController:detailVc animated:YES];
}

// 区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// 数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.homeModelArray.count;
}

// 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [HomeCell heightForCell:self.homeModelArray[indexPath.row]];
}

// 设置分区头部
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HomeHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    
    header.model = self.headerModelArray[section];
    
    //给每个图片添加一个手势 不同手势 点击触发 进入不同的界面
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap1Action:)];
    [header.homeHeaderImage1 addGestureRecognizer:tap1];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap2Action:)];
    [header.homeHeaderImage2 addGestureRecognizer:tap2];
    
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap3Action:)];
    [header.homeHeaderImage3 addGestureRecognizer:tap3];
    
    UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap4Action:)];
    [header.homeHeaderImage4 addGestureRecognizer:tap4];
    
    return header;
}

// 图片1
- (void)tap1Action:(UITapGestureRecognizer *)tap1
{
    //找到父视图控制器
    MainController *mainVc = (MainController *)self.parentViewController;
    [mainVc setScrollViewOffset:KSWidth * 1];
}

// 图片2
- (void)tap2Action:(UITapGestureRecognizer *)tap2
{
    MainController *mainVc = (MainController *)self.parentViewController;
    [mainVc setScrollViewOffset:KSWidth * 2];
}

// 图片3
- (void)tap3Action:(UITapGestureRecognizer *)tap3
{
    MainController *mainVc = (MainController *)self.parentViewController;
    [mainVc setScrollViewOffset:KSWidth * 3];
}

// 图片4
- (void)tap4Action:(UITapGestureRecognizer *)tap4
{
    MainController *mainVc = (MainController *)self.parentViewController;
    [mainVc setScrollViewOffset:KSWidth * 4];
}

// 设置分区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return KSWidth / 1.82;
//    return 0.01;
}

// 设置分区尾高度 设置0.1 防止出现默认高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

// 弹出视图
- (void)alertActionWithTitle:(NSString *)title message:(NSString *)message other:(NSString *)other
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:other style:UIAlertActionStyleDefault handler:nil];
    [alertVc addAction:otherAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
